import { message } from "@pkg";

type FileAcceptType = keyof typeof fileMap;

type SelectOption = {
	type: FileAcceptType[];
	success: (file: File) => void;
	error: () => void;
};

export const fileMap = {
	".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
	".xls": "application/vnd.ms-excel",
	".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
	".doc": "application/msword",
	".txt": "text/plain",
	".pdf": "application/pdf",
	".ppt": "application/vnd.ms-powerpoint",
	".zip": "application/zip",
	".rar": "application/x-rar",
};

export const convertAccept = (typeArray: FileAcceptType[]) => {
	return typeArray.map((item: FileAcceptType) => fileMap[item]);
};

const defaultKey = Object.keys(fileMap) as FileAcceptType[];

export const selectFile = (option: Partial<SelectOption> = {}) => {
	const { type = defaultKey, success, error } = option;
	const ipt = document.createElement("input");
	ipt.setAttribute("type", "file");
	ipt.setAttribute("accept", type.join(","));
	ipt.addEventListener("change", change, false);
	const accept = convertAccept(type);
	function change() {
		const file = ipt.files![0];
		if (accept.includes(file.type)) {
			success && success(file);
		} else {
			message.open({
				type: "error",
				title: "文件类型错误",
				message: `文件格式错误,只能上传${type}格式`,
			});
			error && error();
		}
		ipt.removeEventListener("change", change);
	}
	ipt.click();
};
